﻿using NoodleShop.Api.Messaging;
using NoodleShop.Api.Models;

using Microsoft.Extensions.Hosting;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NoodleShop.Api.HostedServices
{
    public class Kitchen : IHostedService
    {
        private readonly List<OrderModel> _orders = new List<OrderModel>();
        private Timer _timer;
        private readonly IMessagingService _messagingService;

        public Kitchen(IMessagingService messagingService)
        {
            _messagingService = messagingService;
        }

        private bool _isProcessingOrders;


        public void AddOrder(OrderModel newOrder)
        {
            _orders.Add(newOrder);
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(ProcessOrders, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
            return Task.CompletedTask;
        }

        private void ProcessOrders(object state)
        {
            if (!_isProcessingOrders)
            {
                _isProcessingOrders = true;
                while (_orders.Count > 0)
                {
                    var order = _orders.First();

                    // order.Status = "InProgress";
                    // _messagingService.Send("OrderStatusChanged", order.Id, order.Status);

                    order.StatusChanged += SendNotification;

                    order.ChangeStatus("InProgress");
                    
                    Thread.Sleep(500);


                    // order.Status = "Finished";
                    //_messagingService.Send("OrderStatusChanged", order.Id, order.Status);

                    order.ChangeStatus("Finished");

                    _orders.RemoveAt(0);
                }
                _isProcessingOrders = false;
            }
        }

        private void SendNotification(string orderId, string status)
        {
            _messagingService.Send("OrderStatusChanged", orderId, status);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }
    }
}
